﻿using System.Collections.Generic;
using NHibernate.Event;

namespace ContactCenter.AuditEventListener
{
    public class AuditPostCollectionUpdateEventListener : AuditListenerBase, IPostCollectionUpdateEventListener
    {
        public void OnPostUpdateCollection(PostCollectionUpdateEvent evt)
        {
            var entity = evt.AffectedOwnerOrNull;
            string collectionPropertyName = evt.Collection.Role.Substring(evt.Collection.Role.LastIndexOf('.') + 1);

            IEnumerable<object> newState = evt.Collection as IEnumerable<object>;
            IEnumerable<object> oldState = evt.Collection.StoredSnapshot as IEnumerable<object>;

            // Added collection items
            HashSet<object> newStateHash = new HashSet<object>(newState);
            newStateHash.ExceptWith(oldState);
            foreach (var item in newStateHash)
            {
                var addedItem = item.GetType().Name + " id: " + evt.Session.GetIdentifier(item);
                PersistAuditInfo(entity, collectionPropertyName, string.Empty, addedItem, AuditActions.Inserted, evt.Session);
            }

            // Removed collection items
            HashSet<object> oldStateHash = new HashSet<object>(oldState);
            oldStateHash.ExceptWith(newState);
            foreach (var item in oldStateHash)
            {
                var removedItem = item.GetType().Name + " id: " + evt.Session.GetIdentifier(item);
                PersistAuditInfo(entity, collectionPropertyName, string.Empty, removedItem, AuditActions.Deleted, evt.Session);
            }
        }
    }
}
